package king.dominic.jlibrary.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresPermission;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;

/**
 * Created by king on 2017/4/12.
 * CommonUtils
 */

public class CommonUtils {
    public static final String SYS_EMUI = "sys_emui";
    public static final String SYS_MIUI = "sys_miui";
    public static final String SYS_FLYME = "sys_flyme";
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";
    private static final String KEY_EMUI_API_LEVEL = "ro.build.hw_emui_api_level";
    private static final String KEY_EMUI_VERSION = "ro.build.version.emui";
    private static final String KEY_EMUI_CONFIG_HW_SYS_VERSION = "ro.confg.hw_systemversion";

    public static boolean isEMUI(){
        return SYS_EMUI.equals(getSystem());
    }

    public static String getSystem(){
        String SYS=null;
        try {
            Properties prop= new Properties();
            prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
            if(prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                    || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                    || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null){
                SYS = SYS_MIUI;//小米
            }else if(prop.getProperty(KEY_EMUI_API_LEVEL, null) != null
                    ||prop.getProperty(KEY_EMUI_VERSION, null) != null
                    ||prop.getProperty(KEY_EMUI_CONFIG_HW_SYS_VERSION, null) != null){
                SYS = SYS_EMUI;//华为
            }else if(getMeizuFlymeOSFlag().toLowerCase().contains("flyme")){
                SYS = SYS_FLYME;//魅族
            }
        } catch (IOException e){
            e.printStackTrace();
            return null;
        }
        return SYS;
    }

    public static String getMeizuFlymeOSFlag() {
        return getSystemProperty("ro.build.display.id", "");
    }

    private static String getSystemProperty(String key, String defaultValue) {
        try {
            Class<?> clz = Class.forName("android.os.SystemProperties");
            Method get = clz.getMethod("get", String.class, String.class);
            return (String)get.invoke(clz, key, defaultValue);
        } catch (Exception e) {
        }
        return defaultValue;
    }

    public static boolean checkMobile(String mobile) {
        return !(TextUtils.isEmpty(mobile) || mobile.length() != 11)
                && (mobile.startsWith("13") || mobile.startsWith("14")
                || mobile.startsWith("15") || mobile.startsWith("17")
                || mobile.startsWith("18"));
    }
    public static String getVersionName(Context context) {
        if (context == null) return "0.0";
        PackageManager manager = context.getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "0.0";

    }
    public static int getVersionCode(Context context) {
        if (context == null) return -1;
        PackageManager manager = context.getPackageManager();
        PackageInfo info;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;

    }

    private CommonUtils() {
    }

    /**
     * 全角转半角
     *
     * @param input
     * @return output
     */
    public static String fullToHalf(String input) {
        if (null == input || "".equals(input.trim())) {
            return null;
        }
        char[] array = input.toCharArray();
        for (int i = 0; i < array.length; i++) {
            // 全角空格转换为半角空格
            if (array[i] == '\u3000') {
                array[i] = '\u0020';
                // 除空格外的其他字符转换
            } else if (array[i] > '\uff00' && array[i] < '\uff5f') {
                //65248是全角和半角的Unicode值相差
                array[i] = (char) (array[i] - 65248);
            }
        }
        return new String(array);
    }

    /**
     * 半角转换为全角
     *
     * @param input
     * @return　output
     */
    public static String halfToFull(String input) {
        if (null == input || "".equals(input.trim())) {
            return null;
        }
        char[] array = input.toCharArray();
        for (int i = 0; i < array.length; i++) {
            //半角空格转换为全角空格
            if (array[i] == '\u0020') {
                array[i] = '\u3000';
                //除空格外的半角字符转换为全角字符
            } else if (array[i] > '\u0020' && array[i] < '\u007f') {
                array[i] = (char) (array[i] + 65248);
            }
        }
        return new String(array);
    }

    @SuppressLint("HardwareIds")
    @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
    public static String androidID(Context context) {
        TelephonyManager telephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyMgr.getDeviceId();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static String androidDeviceId() {
        return "35" + //we make this look like a valid IMEI
                Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.SUPPORTED_ABIS.length % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10;//13 digits
    }

    public static boolean isMobileWrong(String mobile) {
        return !isMobileRight(mobile);
    }

    public static boolean isMobileRight(String mobile) {
        return !(TextUtils.isEmpty(mobile) || mobile.length() != 11)
                && (mobile.startsWith("13") || mobile.startsWith("14")
                || mobile.startsWith("15") || mobile.startsWith("17")
                || mobile.startsWith("18"));
    }

    public static void gotoCallTelPhoneUI(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        context.startActivity(intent);
    }

    @RequiresPermission(Manifest.permission.CALL_PHONE)
    public static void callTelPhone(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        context.startActivity(intent);
    }

    /**
     * @param msg msg
     * @return String
     */
    public static String md5Encrypt(@NonNull String msg) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("md5");
            byte[] bytes = digest.digest(msg.getBytes());
            StringBuilder builder = new StringBuilder();
            for (byte b : bytes) {
                int v = b & 255;
                String str = Integer.toHexString(v);
                if (str.length() == 1)
                    builder.append("0");

                builder.append(str);
            }
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return msg;
    }

}
